﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace COC.Util
{
	public class Intersection
	{
		public static float[] GetIntersection(BoundingSphere sphere, Ray ray)
		{
			float a, b, c, discrm;
			Vector3 pMinusC = ray.Position - sphere.Center;
			a = Vector3.Dot(ray.Direction, ray.Direction);
			b = 2 * Vector3.Dot(ray.Direction, pMinusC);
			c = Vector3.Dot(pMinusC, pMinusC) - sphere.Radius * sphere.Radius;
			discrm = b * b - 4 * a * c;
			float sqrtDiscrm = (float)Math.Sqrt(discrm);

			if (discrm > 0)
			{
				return new float[2] { (-b + sqrtDiscrm) / (2 * a), (-b - sqrtDiscrm) / (2 * a) };
			}
			else if (discrm == 0)
			{
				return new float[1] { -b / (2 * a) };
			}
			else
			{
				return null;
			}
		}

		public static void EnlargeBoundingBox(ref BoundingBox bb, Vector3 min, Vector3 max)
		{
			bb.Min.X = Math.Min(bb.Min.X, min.X);
			bb.Min.Y = Math.Min(bb.Min.Y, min.Y);
			bb.Min.Z = Math.Min(bb.Min.Z, min.Z);

			bb.Max.X = Math.Max(bb.Max.X, max.X);
			bb.Max.Y = Math.Max(bb.Max.Y, max.Y);
			bb.Max.Z = Math.Max(bb.Max.Z, max.Z);
		}
	}
}